package com.jc.nio.process;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import com.jc.nio.handlers.NioReadHandler;
import com.jc.nio.handlers.NioWriteHandler;

/**
 * 具体业务处理类，根据文件的路径对文件进行加载<br/>
 * <br/>
 * 在这个处理类中要注意构造请求报文，完成对请求的响应，这个类现在还只是支持静态页面的加载而已
 * 
 * @author Joeson
 * @since 2014/05
 * @version 01
 * 
 */
public class Processor
{

	private SocketChannel channel = null;
	private NioReadHandler readHandler = null;
	private NioWriteHandler writeHandler = null;

	private HttpOperation operation = null;
	/**
	 * 用来接受请求报文
	 */
	private ByteBuffer receive = ByteBuffer.allocate(2048);
	/**
	 * 用来发送响应报文头
	 */
	private ByteBuffer send = ByteBuffer.allocate(1024 * 100);

	public Processor()
	{
		operation = new HttpOperation(this);
		readHandler = new NioReadHandler(operation, receive);
		writeHandler = new NioWriteHandler(send);
	}

	// 进行get处理时候的一些属性
	private boolean fileExists = false;
	private boolean fileType = false;
	private String fileName = null;

	/**
	 * 设置属性，为每次重新处理一个通道时都必须先为该类设置一下新的请求属性值
	 * 
	 * @param channel
	 *            将要处理的通道
	 */
	private void initChannel(SocketChannel channel)
	{
		this.channel = channel;

		// 对缓冲区内容先进行清理
		send.clear();
		receive.clear();

		operation.initAttribute(send);
		fileExists = false;
		fileType = false;
		fileName = null;
	}

	/**
	 * 处理请求的核心函数
	 * 
	 * @throws Exception
	 */
	public void processRequest(SocketChannel channel)
	{
		if (channel == null)
		{
			System.err.println("处理的通道不能为空--Processor.processRequest()");
			return;
		}

		// 每次处理的时候都必须做一些准备工作
		initChannel(channel);

		readHandler.handdler(channel);
		operation.get(fileExists, fileType, fileName);
		writeHandler.handdler(channel);

		try
		{
			channel.close();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 设置文件是否存在
	 * 
	 * @param fileExists
	 */
	public void setFileExists(boolean fileExists)
	{
		this.fileExists = fileExists;
	}

	/**
	 * 设置文件是否文件类型符合
	 * 
	 * @param fileType
	 */
	public void setFileType(boolean fileType)
	{
		this.fileType = fileType;
	}

	/**
	 * 设置文件名称
	 * 
	 * @param fileName
	 */
	public void setFileName(String fileName)
	{
		this.fileName = fileName;
	}

}
